#

function file-linked-make-softlink()
{
    local OUT_LINK=$1
    local ORI_FLIE=$2
    if [ ! -f "$ORI_FLIE" ] && [ ! -d "$ORI_FLIE" ]; then
        #echo File/Dir not found
        return 1
    fi
    rm $OUT_LINK
    ln -s $ORI_FLIE $OUT_LINK
    echo "ln -s $ORI_FLIE $OUT_LINK"
    return 0
}

# 将 绝对路径的软链接 修复为 相对路径 的链接
# fix absolutely soft linked to relative
function file-linked-make-absolutely-link-to-relative ()
{
#用法： 传入软链接中需要去掉的绝对路径头
#
# 例如：
#   ls -al
#   lrwxrwxrwx   1 schips schips    49 1月  14 13:43 Android.bp -> /path_wrong/SM6115-11-r12/build/soong/root.bp
#
#   那么，只需：
#   file-fix-absolutely-softLinked-to-relative  /path_wrong/SM6115-11-r12/

#   ls -al
#   lrwxrwxrwx   1 schips schips    49 1月  14 13:45 Android.bp -> build/soong/root.bp

    local TMPLIST=`tmp-gen-safe-file`


    # 多余的字符
    local SURPLUS=$1

    find . -type l > ${TMPLIST}

    local CUT_CNT=`echo $SURPLUS | wc -c`

    local res=""
    local TOFILE=""
    local HEAD=""
    local STR_SHOULD=""
    for LNFILE in `cat $TMPLIST`
    do
        if [ -h "$LNFILE" ];then

            res=`ls $LNFILE -l`

            TOFILE=`echo $res | awk -F\> '{print $2}'`
            if [ ! -f "$TOFILE" ]; then
                HEAD=`echo ${TOFILE}|cut -c 1`

                if [ "$HEAD" = "/" ]; then
                    STR_SHOULD=`echo $TOFILE| cut -c ${CUT_CNT}-`
                    if [ -z "$STR_SHOULD" ]; then
                        return
                    fi

                    #echo "[Missing] $LNFILE ----> $TOFILE"
                    #echo "[should] $LNFILE ----> $STR_SHOULD"

                    file-linked-make-softlink $LNFILE $STR_SHOULD || echo "[Failed] $LNFILE : $TOFILE"
                fi
            fi
        fi
    done

    rm ${TMPLIST}
}

# 把软链接变为常规文件
function file-linked-make-absolutely-linke-to-regular-file ()
{
    if [ ! -d "$1"]; then
        echo "Need dir"
        return 1
    fi

    local TMPLIST=`tmp-gen-safe-file`

    find . -type f > ${TMPLIST}

    for LNFILE in `cat $TMPLIST`
    do
        if [ -h "$LNFILE" ];then

            BASE=`pwd`
            DSTDIR=`dirname  $LNFILE`
            res=`ls $LNFILE -l`
            #echo $DSTDIR
            SCRFILE=`basename $LNFILE`
            TOFILE=`echo $res | awk -F\> '{print $2}'`

            ## 删除 源链接
            rm $LNFILE
            ## 拷贝
            bash <<EOF
            cd $DSTDIR
            cp $TOFILE $SCRFILE
EOF
        fi

    done

    rm ${TMPLIST}
}

